﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;
using Common.DBOper;

namespace VibrationTest
{
    public partial class frmSet : Form
    {
        public frmSet()
        {
            InitializeComponent();
        }
        Cls_SocketSet sockset = new Cls_SocketSet();
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.txt_IP.Text.Trim() == "" || this.txt_Port.Text.Trim() == "")
            {
                MessageBox.Show("IP地址和端口号都不能为空", "提示");
                return;
            }

            if (IsValidIP(this.txt_IP.Text.Trim()) == false)
            {
                MessageBox.Show("IP地址格式错误", "提示");
                return;
            }

            if (sockset.UpdateSocketSet(this.txt_IP.Text.Trim(), this.txt_Port.Text.Trim(),Convert.ToInt32(this.cmb_channelCount.Text)) > 0)
            {
                if(Program.formchannelset!=null)
                {
                    if (Program.formchannelset.ChannelCount != Convert.ToInt32(this.cmb_channelCount.Text))
                    {
                        Program.formchannelset.LoadChannelSet();
                    }
                }

                MessageBox.Show("保存成功", "提示");
            }
            else 
            {
                MessageBox.Show("保存失败", "提示");
            }
        }

        private void frmSet_Load(object sender, EventArgs e)
        {
            Cls_Scoket socketset = sockset.GetSocket();
            this.txt_IP.Text = socketset.IpAddress;
            this.txt_Port.Text = socketset.Port.ToString();
            this.cmb_channelCount.Text = socketset.ChannelCount.ToString();
        }

        private void txt_Port_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            {

                e.Handled = true;

            }
        }


        public bool IsValidIP(string ip)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(ip, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
            {
                string[] ips = ip.Split('.');
                if (ips.Length == 4 || ips.Length == 6)
                {
                    if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
                        return true;
                    else
                        return false;
                }
                else
                    return false;

            }
            else
                return false;
        }

    }
}
